<?php

namespace App\Validate;

use EasySwoole\Validate\Validate;

class Base
{
    // 验证规则
    public $rules = [];

    // 验证错误消息提示
    public $messages = [];

    // 验证字段的别名
    public $alias = [];

    // 验证场景
    public $sence = [];

    /**
     * 验证失败返回 false，或者用户可以抛出异常，验证成功返回 true
     * @param array data 验证数据
     * @param string sence 场景
     * @return bool
     */
    public function validate($data, $sence = '')
    {
        if (!$this->rules) {
            return true;
        }
        $rules = $this->rules;
        if ($sence && isset($this->sence[$sence])) {
            $rules = [];
            foreach ($this->rules as $key => $val) {
                if (in_array($key, $this->sence[$sence])) {
                    $rules[$key] = $val;
                }
            }
        }
        $validate = Validate::make($rules, $this->messages, $this->alias);
        $validate = $this->special($validate, $data);
        if ($validate->validate($data)) {
            return true;
        }
        return $validate->getError()->__toString();
    }

    /**
     * @description: 特殊规则
     * @param Validate $validate 验证器
     * @param array $data 验证数据
     * @return {*}
     */
    public function special($validate, $data)
    {
        return $validate;
    }
}